package com.securitytrace.service.impl;

import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Property;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.securitytrace.model.Address;
import com.securitytrace.model.Role;
import com.securitytrace.model.User;
import com.securitytrace.service.UserService;
import com.securitytrace.service.exception.AccountExistException;
import com.securitytrace.service.exception.IncorrectAccountOrPasswordException;

public class UserServiceImpl extends HibernateDaoSupport implements UserService {
	

	public void create(User user, long roleId, long addressId)
			throws AccountExistException {
		Role role = getHibernateTemplate().get(Role.class, roleId);
		Address address = getHibernateTemplate().get(Address.class, addressId);
		user.setAddress(address);
		user.setRole(role);
		this.add(user);
	}

	@SuppressWarnings("unchecked")
	public User login(String account, String password)
			throws IncorrectAccountOrPasswordException {
		DetachedCriteria query = DetachedCriteria.forClass(User.class);
		query.add(Property.forName("account").eq(account));
		query.add(Property.forName("password").eq(password));
		List<User> list = query.getExecutableCriteria(getSession()).list();
		if(list == null || list.size() == 0) {
			throw new IncorrectAccountOrPasswordException();
		}
		return list.get(0);
	}

	public void updatePassword(long id, String password) {
		User user = getById(id);
		user.setPassword(password);
		update(user);
	}
	
	public long getTotalCount() {
		DetachedCriteria criteria = DetachedCriteria.forClass(User.class);
		criteria.setProjection(Projections.count("id"));
		return (Long) criteria.getExecutableCriteria(getSession()).uniqueResult();
	}

	public boolean exist(long id) {
		User obj = this.getHibernateTemplate().get(User.class, id);
		return obj != null;
	}

	public User getById(long id) {
		return getHibernateTemplate().get(User.class, id);
	}
	
	@SuppressWarnings("unchecked")
	public List<User> getList() {
		return getSession().createCriteria(User.class).list();
	}

	@SuppressWarnings("unchecked")
	public List<User> getListByPage(int start, int pageSize) {
		return getSession().createCriteria(User.class)
					.setFirstResult(start).setMaxResults(pageSize).list();
	}

	public void deleteById(long id) {
		getHibernateTemplate().delete(getHibernateTemplate().get(User.class, id));
	}

	public void add(User obj) {
		getHibernateTemplate().save(obj);
	}

	public void update(User obj) {
		getHibernateTemplate().update(obj);
	}
	

}
